package pers.cz.filter;

import cn.hutool.core.date.DateUtil;
import pers.cz.exception.ErrorCode;
import pers.cz.exception.GeneralException;
import pers.cz.mapper.PostgirlDtlMapper;
import pers.cz.mapper.PostgirlMapper;
import pers.cz.model.Postgirl;
import pers.cz.model.PostgirlDtl;
import pers.cz.model.Role;
import pers.cz.pub.BeanHelper;
import pers.cz.session.ContextHolder;
import pers.cz.session.User;
import pers.cz.spring.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @program: PostGirl-panent
 * @description: loadUserByUserNameServiceImpl
 * @author: Cheng Zhi
 * @create: 2021-03-30 12:49
 **/
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private BeanHelper beanHelper;

    /**
     * 根据用户名查询用户信息，用于登录
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        Postgirl user = SpringContextUtil.getBean(PostgirlMapper.class).loadUserByUsername(userName);
        if (user == null) {
            throw new GeneralException(ErrorCode.FILE_ANALYSE_ERROR);
        }
        Integer userId = user.getUserId();
        List<Role> roles = SpringContextUtil.getBean(PostgirlMapper.class).selectRoleByUserId(userId);
        user.setRoles(roles);

        // 查询用户明细信息
        PostgirlDtl postgirlDtl = SpringContextUtil.getBean(PostgirlDtlMapper.class).selectByPrimaryKey(userId);
        user.setRealName(postgirlDtl.getRealName());
        user.setPhoneId(String.valueOf(postgirlDtl.getPhoneId()));
        // 每次登录后都需要更新用户表的最后登录时间,异步去执行。
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // 异步修改最后登录时间
                Postgirl postgirl = new Postgirl();
                postgirl.setUserId(userId);
                postgirl.setUpdateDate(DateUtil.date());
                SpringContextUtil.getBean(PostgirlMapper.class).updateByPrimaryKeySelective(postgirl);
                return null;
            }
        });

        ExecutorService executor = Executors.newFixedThreadPool(1);
        executor.submit(futureTask);
        executor.shutdown(); // shutdown()不是立即关闭，是指将已经提交的任务处理完才关闭，调用了shutdown之后不可以再提交任务。

        return (UserDetails) user;
    }


}
